#pragma once

#include "../comm/util.hpp"
#include "../comm/log.hpp"
#include "../comm/sqlManager.hpp"

struct Comment {
    int comment_id;         // 评论的唯一标识符
    int user_id;            // 用户唯一标识符
    int article_id;         // 文章唯一标识符
    // std::string user_name;  // 用户名
    std::string content;    // 评论内容
    std::string comment_time; // 评论时间
};

class CommentManager {
private:
    ns_sql::MySQLManager _dbManager;
    std::mutex _mutex; 

public:
    CommentManager(const std::string &host, const std::string &user, const std::string &password, const std::string &dbName) {
        LOG_DEBUG() << "Initializing CommentManager with database: " << dbName;
        if (!_dbManager.openDatabase(host, user, password, dbName)) {
            LOG_ERROR() << "Failed to open database: " << _dbManager.getErrorMessage();
        }
    }

    ~CommentManager() {
        _dbManager.closeDatabase();
    }

    // 添加评论
    bool addComment(const int &userId, const int &articleId, const std::string &content, const std::string &username) {
        std::unique_lock<std::mutex> lock(_mutex);  // 加锁，作用域结束时自动解锁
        // LOG_DEBUG() << "Adding comment for article " << articleId << " by user " << userId;

        // 构建 SQL 查询，使用 std::to_string 转换整数参数为字符串
        std::string query = "INSERT INTO comments (user_id, article_id, content, comment_time) VALUES (" +
                            std::to_string(userId) + ", " + std::to_string(articleId) + ", '" + 
                            content + "', '" + ns_util::TimeUtil::GetDateTime() + "')";

        // 执行插入语句
        bool result = _dbManager.executeQuery(query);
        if (!result) {
            LOG_ERROR() << "Failed to add comment: " << _dbManager.getErrorMessage();
            return false;
        }

        // LOG_DEBUG() << "Comment added successfully.";
        return true;
    }

    // 删除评论
    bool deleteComment(const std::string &commentId) {
        std::unique_lock<std::mutex> lock(_mutex);
        // LOG_DEBUG() << "Deleting comment " << commentId;

        // 构造删除查询语句，根据 comment_id 删除评论
        std::string query = "DELETE FROM comments WHERE comment_id = " + commentId;

        // 执行删除语句
        bool result = _dbManager.executeQuery(query);
        if (!result) {
            LOG_ERROR() << "Failed to delete comment: " << _dbManager.getErrorMessage();
            return false;
        }

        LOG_DEBUG() << "Comment deleted successfully.";
        return true;
    }

    // 获取所有评论
    bool getAllCommentsByArticleId(const std::string &articleId, std::vector<Comment> &commentList) {
        std::unique_lock<std::mutex> lock(_mutex);
        // LOG_DEBUG() << "Retrieving all comments for article " << articleId;

        // 构造查询语句
        std::string query = "SELECT comment_id, user_id, article_id, content, comment_time uesr_name FROM comments WHERE article_id = " + articleId;

        // 获取查询结果
        ns_sql::MySQLManager::MySQLResult result = _dbManager.getResult(query);

        // 检查是否有数据
        if (!result.next()) {
            LOG_ERROR() << "No comments found or query failed: " << _dbManager.getErrorMessage();
            return false;
        }

        // 处理结果集并填充到 commentList
        do {
            try {
                Comment comment;
                comment.comment_id = result.getInt(0);   // 获取 comment_id
                comment.user_id = result.getInt(1);
                comment.article_id = result.getInt(2);
                comment.content = result.getString(3).empty() ? "" : result.getString(3); // 处理 content 字段
                comment.comment_time = result.getString(4).empty() ? "" : result.getString(4); // 处理 comment_time 字段

                commentList.push_back(comment);
            } catch (const std::exception &e) {
                LOG_ERROR() << "Error processing comment data: " << e.what();
                return false;
            }
        } while (result.next());

        // LOG_DEBUG() << "Comments retrieved successfully.";
        return true;
    }

    // 获取所有评论
    bool getAllComments(std::vector<Comment> &commentList) {
        std::unique_lock<std::mutex> lock(_mutex);  // 加锁，确保线程安全

        // 构造查询语句，获取所有评论
        std::string query = "SELECT comment_id, user_id, article_id, content, comment_time FROM comments";

        // 获取查询结果
        ns_sql::MySQLManager::MySQLResult result = _dbManager.getResult(query);

        // 检查是否有数据
        if (!result.next()) {
            LOG_ERROR() << "No comments found or query failed: " << _dbManager.getErrorMessage();
            return false;
        }

        // 处理结果集并填充到 commentList
        do {
            try {
                Comment comment;
                comment.comment_id = result.getInt(0);   // 获取 comment_id
                comment.user_id = result.getInt(1);      // 获取 user_id
                comment.article_id = result.getInt(2);   // 获取 article_id
                comment.content = result.getString(3).empty() ? "" : result.getString(3); // 获取 content 字段
                comment.comment_time = result.getString(4).empty() ? "" : result.getString(4); // 获取 comment_time 字段

                commentList.push_back(comment);
            } catch (const std::exception &e) {
                LOG_ERROR() << "Error processing comment data: " << e.what();
                return false;
            }
        } while (result.next());

        LOG_DEBUG() << "Comments retrieved successfully.";
        return true;
    }

};
